<!--收集系统日志-->
<template>
  <div>
    <a-modal :title="$t('Collect-sys-log')" :visible="visible" width='40%' @cancel="handleCancel" :maskClosable='false'
      v-dragModal>
      <!-- @ok="handleOk" -->
      <!-- :cancelText="$t('Cancel')" :okText="$t('Sure')"  -->
      <a-form :form='form'>
        <!--模块-->
        <a-form-item :label="$t('Modular')" v-bind='formlayout' has-feedback>
          <a-select v-decorator="['module_data', {
            rules: [{ required: true, message: $t('Choose') + $t('Modular') }],
          }]" :placeholder="$t('Choose') + $t('Modular')" @change="changeModule">
            <template v-if="$store.state.language == 'zh'">
              <a-select-option v-for="(item, index) in moduleData" :value='item.value' :key="index">{{ item.title
                }}</a-select-option>
            </template>
            <template v-else>
              <a-select-option v-for="(item, index) in moduleData" :value='item.value' :key="index">{{ item.title_en
                }}</a-select-option>
            </template>
          </a-select>
        </a-form-item>
        <!--子模块-->
        <a-form-item :label="$t('Submodule')" v-bind='formlayout' has-feedback
          v-if="moduleValue != -1 && moduleValue != 'all' && moduleValue != 'AllOSLog'">
          <a-select v-decorator="['child_module', {
            rules: [{ required: true, message: $t('Choose') + $t('Submodule') }],
          }]" :placeholder="$t('Choose') + $t('Submodule')">
            <template v-if="$store.state.language == 'zh'">
              <a-select-option v-for="(item, index) in childModules" :value='item.value' :key="index">{{ item.title
                }}</a-select-option>
            </template>
            <template v-else>
              <a-select-option v-for="(item, index) in childModules" :value='item.value' :key="index">{{ item.title_en
                }}</a-select-option>
            </template>
          </a-select>
        </a-form-item>
        <!--时间范围-->
        <a-form-item :label="$t('Time-frame')" v-bind='formlayout' has-feedback v-if="moduleValue != 'AllOSLog'">
          <a-range-picker v-decorator="['time', {
            rules: [{ required: true, message: $t('Choose') + $t('Time-frame') },]
          }]" :show-time="{ format: 'YYYY-MM-DD' }" format="YYYY-MM-DD"
            :placeholder="[$t('Start-time'), $t('End-time')]" style="width:100%" :locale="rangePickerLocal"
            @change="onChange" />
          <!-- @ok="onOk" -->
        </a-form-item>
        <div style="margin-left:25%" v-if="moduleValue != 'AllOSLog'">
          <a-radio-group v-model="timeRadioValue" @change="onChangeTimeRadio">
            <template v-if="$store.state.language == 'zh'">
              <a-radio v-for="(item, index) in timeRadios" :value="item.value" :key="index">{{ item.title }}</a-radio>
            </template>
            <template v-else>
              <a-radio v-for="(item, index) in timeRadios" :value="item.value" :key="index">{{ item.title_en
                }}</a-radio>
            </template>
          </a-radio-group>
        </div>
      </a-form>
      <template slot="footer">
        <a-button key="back" @click="handleCancel" style="width:90px">
          {{ $t('Cancel') }}
        </a-button>
        <a-button key="submit" type="primary" @click="handleOk" :loading="isLoadingSubmit" style="width:90px">
          {{ $t('Sure') }}
        </a-button>
      </template>
    </a-modal>
  </div>
</template>

<script>
import { getNDayOfTimeStamp, changeToYearMonthDay, getNowTimeStamp } from '../../../../../untils/formatTime'
import request from '@/request/request'

export default {
  props: ['visible', 'targetRow'],
  data() {
    return {
      form: this.$form.createForm(this),
      formlayout: {
        labelCol: { span: 6 },
        wrapperCol: { span: 18 }
      },
      isAllLog: false,
      moduleData: [
        { title: '全部', title_en: 'All', value: 'all' },
        { title: '存储引擎', title_en: 'Storage engine', value: 'StorageLog' },
        { title: '管理系统', title_en: 'Management system', value: 'ManageLog' },
        { title: '操作系统', title_en: 'Operating system', value: 'OSLog' },
        { title: '完整系统日志', title_en: 'All System Log', value: 'AllOSLog' }
      ],
      moduleValue: -1,
      childModules: [],
      childModules1: [ //存储引擎
        { title: '全部', title_en: 'all', value: 'all' },
        { title: '对象存储', title_en: 'Object Storage', value: 'rgw' },
        { title: '集群信息', title_en: 'Cluster information', value: 'ceph' },
        { title: '文件存储', title_en: 'File store', value: 'mds' },
        { title: '管理服务', title_en: 'Management service', value: 'mgr' },
        { title: '监控服务', title_en: 'Monitoring service', value: 'mon' },
        { title: 'OSD服务', title_en: 'OSD service', value: 'osd' },
        { title: 'NFS服务', title_en: 'Services for NFS', value: 'ganesha' },
        { title: 'CIFS服务', title_en: 'CIFS Services', value: 'samba' },
        { title: 'ISCSI服务', title_en: 'ISCSI Services', value: 'iscsi' },
      ],
      childModules2: [ //管理系统
        { title: '全部', title_en: 'all', value: 'all' },
        { title: '内存共享服务', title_en: 'Memory sharing service', value: 'redis' },
        { title: '后台服务', title_en: 'Back-up services', value: 'seabed' },
      ],
      childModules3: [ //操作系统
        { title: '全部', title_en: 'all', value: 'all' },
        { title: '安全', title_en: 'Security', value: 'secure' },
        { title: '进程记录', title_en: 'Progress record', value: 'pacct' },
        { title: '启动记录', title_en: 'Startup record', value: 'boot' },
        { title: '系统日志', title_en: 'System log', value: 'messages' },
        { title: '开机信息', title_en: 'Power on information', value: 'dmesg' },
      ],
      rangePickerLocal: {
        "lang": {
          "placeholder": "Select date",
          "rangePlaceholder": ["Start date", "End date"],
          "today": "Today",
          "now": "Now",
          "backToToday": "Back to today",
          "ok": this.$t('Sure'),
          "clear": "Clear",
          "month": "Month",
          "year": "Year",
          "timeSelect": this.$t('Select-time-picker'),
          "dateSelect": this.$t('Select-date-picker'),
          "monthSelect": "Choose a month",
          "yearSelect": "Choose a year",
          "decadeSelect": "Choose a decade",
          "yearFormat": "YYYY",
          "dateFormat": "M/D/YYYY",
          "dayFormat": "D",
          "dateTimeFormat": "M/D/YYYY HH:mm:ss",
          "monthFormat": "MMMM",
          "monthBeforeYear": true,
          "previousMonth": "Previous month (PageUp)",
          "nextMonth": "Next month (PageDown)",
          "previousYear": "Last year (Control + left)",
          "nextYear": "Next year (Control + right)",
          "previousDecade": "Last decade",
          "nextDecade": "Next decade",
          "previousCentury": "Last century",
          "nextCentury": "Next century"
        },
      },
      timeRadioValue: -1,
      timeRadios: [
        { title: '近一天', title_en: 'Nearly one day', value: 0 },
        { title: '近三天', title_en: 'Nearly three days', value: 1 },
        { title: '近一周', title_en: 'Nearly a week', value: 2 },
        { title: '近一月', title_en: 'Nearly a month', value: 3 },
      ],
      timeRange: [],
      isLoadingSubmit: false,
    }
  },
  mounted() {

  },
  methods: {
    //收集日志
    handleOk(e) {
      e.preventDefault();
      this.form.validateFields(async (err, value) => {
        if (!err) {
          this.isLoadingSubmit = true;
          this.$message.success(this.$t('Collecting'));
          //判断当前是数组还是对象（选择框还是单个选)
          if (this.targetRow.length) {
            // this.targetRow.forEach(async (item,index) => {
            //   let paramsObj = {
            //     // user_id: localStorage.getItem('user_id'),
            //     machine_id: item.machine_id,
            //     module: value.module_data,
            //     submodule: value.child_module,
            //     start_date: this.timeRange[0],
            //     end_date: this.timeRange[1]
            //   }
            //   let res = await this.collectLogRequest(this.$protocolStr + item.manage_ip + this.$portStr, paramsObj);
            //   if(res.data.flag != 0) {
            //     this.model(res.data.id) //返回模板
            //     this.notice(res.data.id,res.data.params,res.data.flag) //通知列表显示
            //   }
            //   if(index == this.targetRow.length -1) {
            //     this.model(res.data.id) //返回模板
            //     this.notice(res.data.id,res.data.params,res.data.flag) //通知列表显示
            //   }
            //   this.updateData();
            // });


            this.targetRow.map(async (item, index) => {
              let paramsObj = {}

              if (this.isAllLog) {
                paramsObj = {
                  machine_id: item.machine_id,
                  module: "AllOSLog",
                  submodule: "sosreport",
                  start_date: 1732532778,
                  end_date: "1732532778",
                  user_id: localStorage.getItem('user_id'),
                  ipaddr: item.manage_ip
                }
              } else {
                paramsObj = {
                  // user_id: localStorage.getItem('user_id'),
                  machine_id: item.machine_id,
                  module: value.module_data,
                  submodule: value.child_module,
                  start_date: this.timeRange[0],
                  end_date: this.timeRange[1],
                  user_id: localStorage.getItem('user_id'),
                  ipaddr: item.manage_ip
                }

              }
              let res = await this.collectLogRequest(paramsObj);
              this.model(res.data.id) //返回模板
              this.notice(res.data.id, res.data.params, res.data.flag) //通知列表显示
              this.isLoadingSubmit = false;
              this.updateData();
              // return res;
            });
            // const collectResponse = await Promise.all(results);
            // let okTipInfo = this.$t('Collect-ok-machine') + '：';//收集成功的提示
            // let noTipInfo = this.$t('Collect-no-machine') + '：';//收集失败的提示
            // let successMachine = 0;
            // let errorMachine = 0;
            // collectResponse.forEach((item, index) => {
            //   // this.model(item.data.id); //返回模板
            //   let machine = '';
            //   let colonIndex = item.config.url.lastIndexOf(':');
            //   machine = item.config.url.substring(7, colonIndex);
            //   if (item.data.flag == 0) {
            //     successMachine++;
            //     okTipInfo += machine + '、';
            //   } else {
            //     errorMachine++;
            //     noTipInfo += machine + '、';
            //   }
            //   if (index == collectResponse.length - 1) {
            //     okTipInfo = okTipInfo.substring(0, okTipInfo.length - 1);
            //     noTipInfo = noTipInfo.substring(0, noTipInfo.length - 1);
            //     if (successMachine == 0) {
            //       okTipInfo = '';
            //     }
            //     if (errorMachine == 0) {
            //       noTipInfo = '';
            //     }
            //     this.$notification.open({
            //       message: this.$t('Operation-prompt'),
            //       description: `${okTipInfo}；${noTipInfo}`,
            //     });
            //     this.isLoadingSubmit = false;
            //     this.updateData();
            //   }
            // })

          } else {
            let paramsObj = {}
            if (this.isAllLog) {
              paramsObj = {
                machine_id: this.targetRow.machine_id,
                module: "AllOSLog",
                submodule: "sosreport",
                start_date: 1732532778,
                end_date: "1732532778",
                user_id: localStorage.getItem('user_id'),
                ipaddr: this.targetRow.manage_ip
              }
            } else {
              paramsObj = {
                // user_id: localStorage.getItem('user_id'),
                machine_id: this.targetRow.machine_id,
                module: value.module_data,
                submodule: value.child_module,
                start_date: this.timeRange[0],
                end_date: this.timeRange[1],
                user_id: localStorage.getItem('user_id'),
                ipaddr: this.targetRow.manage_ip
              }
            }
              let res = await this.collectLogRequest(paramsObj)
              this.model(res.data.id) //返回模板
              this.notice(res.data.id, res.data.params, res.data.flag) //通知列表显示
              this.isLoadingSubmit = false;
              this.updateData();
             
            }
          }
        })
    },

    //更新数据
    updateData() {
      this.$emit('updateTableData');
      this.$store.commit('updateCollectRecord', true); //更新系统日志收集记录
      this.handleCancel();
    },

    // //收集日志请求方法
    collectLogRequest(params) {
      return new Promise((resolve, reject) => {
        // this.$axios.put(ip+ 'logmanage/syslog/', params).then(res => {
        request('put', 'logmanage/syslog/', params).then(res => {
          // console.log('收集日志', res)
          resolve(res);
        }).catch(err => {
          reject(err);
          // console.log(err);
        }).finally(() => {

        })
      })
    },

    //改变模块
    changeModule(value) {
      this.moduleValue = value;

      if (value == 'StorageLog') {//存储引擎
        this.childModules = this.childModules1;
        this.isAllLog = false
      } else if (value == 'ManageLog') {//管理系统
        this.childModules = this.childModules2;
        this.isAllLog = false

      } else if (value == 'OSLog') {//操作系统
        this.childModules = this.childModules3;
        this.isAllLog = false

      } else if (value == 'AllOSLog') {//全部系统日志
        //全部系统日志编辑部分
        this.isAllLog = true
        console.log("value", this.isAllLog)
      }
    },

    //改变时间范围
    onChange(date, dateString) {
      // console.log('date', date);
      // console.log('dateString', dateString);
      //moment对象转为时间戳
      if (date.length != 0) {
        this.timeRange[0] = String(date[0].valueOf()).substring(0, 10);
        this.timeRange[1] = String(date[1].valueOf()).substring(0, 10);
      } else {
        this.timeRange = [];
        this.timeRadioValue = -1;
      }
    },

    //改变单选时间通用函数
    timeChangeFun(day) {
      let startTimeStamp = 0;
      let endTimeStamp = getNowTimeStamp();
      let startTime = '';
      let endTime = '';
      let timestamp = getNDayOfTimeStamp(day); //获取n天的时间戳
      startTimeStamp = endTimeStamp - timestamp;
      startTime = changeToYearMonthDay(startTimeStamp, 'all') //时间戳转为年月日时分秒
      endTime = changeToYearMonthDay(endTimeStamp, 'all') //时间戳转为年月日时分秒
      this.form.setFieldsValue({//最好转成moment对象，这样控制台不会报警告
        time: [startTime, endTime]
      });
      this.timeRange[0] = startTimeStamp;
      this.timeRange[1] = endTimeStamp;
      return {
        startTime,
        endTime,
        startTimeStamp,
        endTimeStamp
      }
    },

    //改变单选时间
    onChangeTimeRadio(e) {
      if (e.target.value == 0) {//近一天
        this.timeChangeFun(1);
      } else if (e.target.value == 1) {//近三天
        this.timeChangeFun(2);
      } else if (e.target.value == 2) {//近一周
        this.timeChangeFun(6);
      } else if (e.target.value == 3) {//近一月
        this.timeChangeFun(29);
      }
    },

    //关闭弹窗
    handleCancel() {
      this.$emit('closeDialog', 'log');
      // this.moduleValue = -1;
    },
  },
}
</script>
<style scoped>
/* 单选框样式 */
::v-deep.ant-radio-wrapper {
  padding: 4px;
  border: 1px solid #999;
  color: #999;
}

::v-deep.ant-radio-wrapper-checked {
  border: 1px solid var(--themeColor);
  color: var(--themeColor);
}
</style>